﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;

namespace Cocon90.Lib.Dal.Tools
{
    /// <summary>
    /// DataTable与List之间的转换
    /// </summary>
    public class DataModel<T> where T : new()
    {
        /// <summary>
        /// DataTable转实体集合
        /// </summary>
        /// <param name="dt">数据表</param>
        /// <returns>泛类列表</returns>
        public List<T> GetList(DataTable table)
        {
            if (table == null) return new List<T>();
            List<T> modes = new List<T>();
            var typeT = typeof(T);
            var props = typeT.GetProperties();
            foreach (System.Data.DataRow dr in table.Rows)
            {
                T obj = (T)Activator.CreateInstance(typeT);
                foreach (var prop in props)
                {
                    if (dr.Table.Columns.Contains(prop.Name))
                    {
                        if (prop.CanWrite)
                        {
                            if (dr[prop.Name] is System.DBNull)
                                prop.SetValue(obj, null, null);
                            else
                                prop.SetValue(obj, dr[prop.Name], null);
                        }
                    }
                }
                modes.Add(obj);
            }
            return modes;
        }
        /// <summary>
        /// 实体集合转DataTable
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public DataTable GetDataTable(IList<T> list)
        {
            //检查实体集合不能为空
            if (list == null || list.Count < 1)
            {
                return null;
            }

            //取出第一个实体的所有Propertie
            Type entityType = list[0].GetType();
            PropertyInfo[] entityProperties = entityType.GetProperties();

            //生成DataTable的structure
            //生产代码中，应将生成的DataTable结构Cache起来，此处略
            var dt = new DataTable();
            foreach (PropertyInfo t in entityProperties)
            {
                dt.Columns.Add(t.Name, t.PropertyType);
            }
            //将所有entity添加到DataTable中
            foreach (object entity in list)
            {
                //检查所有的的实体都为同一类型
                if (entity.GetType() != entityType)
                {
                    continue;
                }
                var entityValues = new object[entityProperties.Length];
                for (int i = 0; i < entityProperties.Length; i++)
                {
                    entityValues[i] = entityProperties[i].GetValue(entity, null);
                }
                dt.Rows.Add(entityValues);
            }
            return dt;
        }
    }
}
